﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using QueryBuilder;
using Telerik.Web.UI;
using System.IO;
using EXAM.Admin.Page_Admin.UsrControl;
using FlexCel.Core;

namespace EXAM.Admin.Page_Admin
{
    public partial class Filters : System.Web.UI.Page
    {
        SQLBuilder _sqlBuilder = new SQLBuilder(processingMode.Details);
        string qdCode = "";
        string queryText = "";
        string _db = "EXA";
        string _connDes = ConfigurationSettings.AppSettings["strDesConnection"].ToString();
        string _connSrc = "";
        string _pathTemp = "~/Template";
        string _pathReport = "~/Report";
        string sErr = "";
        protected void Page_Load(object sender, EventArgs e)
        {

            QueryFilterMenu1.btnExcel.Click += new ImageClickEventHandler(btnExcel_Click);
            QueryFilterMenu1.btnPDF.Click += new ImageClickEventHandler(btnPDF_Click);
            if (!IsPostBack)
            {
                if (Request["qdid"] != null)
                {
                    hdQDCode.Value = Request["qdid"].ToString();
                    BUS.LIST_QDControl ctr = new BUS.LIST_QDControl();
                    DTO.LIST_QDInfo inf = ctr.Get_LIST_QD("EXA", hdQDCode.Value, ref sErr);
                    lbTitle.Text = inf.DESCRIPTN;
                    SQLBuilder.SetConnection(ConfigurationSettings.AppSettings["strConnection"].ToString());
                    SQLBuilder _sqlBuilder = SQLBuilder.LoadSQLBuilderFromDataBase(hdQDCode.Value, "EXA", inf.ANAL_Q0.Trim());
                    Session["sqlbuilder"] = _sqlBuilder;
                }
                else
                {
                    Response.Redirect("Reports.aspx");
                }
            }
        }

        void btnPDF_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                _pathTemp = MapPath(_pathTemp) + "/";
                _pathReport = MapPath(_pathReport) + "/";
                SQLBuilder tmp = Session["sqlbuilder"] as SQLBuilder;
                if (tmp == null)
                {
                    lbErr.Text = "Session is timeout! Please to login again";
                    return;
                }
                ReportGenerator report = new ReportGenerator(tmp, Request["qdid"].ToString(), "", _connDes, _pathTemp, _pathReport);
                //MemoryStream ms = report.ExportPDF(MapPath("~"), qdCode);
                using (MemoryStream ms = report.ExportPDF(_pathTemp))
                {
                    ms.Position = 0;
                    Response.Clear();
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + Request["qdid"].ToString() + ".pdf");
                    Response.AddHeader("Content-Length", ms.Length.ToString());
                    Response.ContentType = "application/pdf";
                    Response.BinaryWrite(ms.ToArray());
                    Response.End();
                }
            }
            catch (Exception ex) { lbErr.Text = ex.Message; }
        }

        void btnExcel_Click(object sender, ImageClickEventArgs e)
        {
            _pathTemp = MapPath(_pathTemp) + "/";
            _pathReport = MapPath(_pathReport) + "/";
            try
            {
                SQLBuilder tmp = Session["sqlbuilder"] as SQLBuilder;
                if (tmp == null)
                {
                    lbErr.Text = "Session is timeout! Please to login again";
                    return;
                }
                ReportGenerator report = new ReportGenerator(tmp, Request["qdid"].ToString(), "", _connDes, _pathTemp, _pathReport);
                ExcelFile file = report.ExportExcel(_pathReport);
                using (MemoryStream ms = new MemoryStream())
                {
                    file.Save(ms);
                    ms.Position = 0;
                    Response.Clear();
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + Request["qdid"].ToString() + ".xls");
                    Response.AddHeader("Content-Length", ms.Length.ToString());
                    Response.ContentType = "application/excel";
                    Response.BinaryWrite(ms.ToArray());
                    Response.End();
                }
            }
            catch (Exception ex) { lbErr.Text = ex.Message; }
        }



        protected void dgvList_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            if (Session["sqlbuilder"] != null)
            {

                _sqlBuilder = (SQLBuilder)Session["sqlbuilder"];
                if (_sqlBuilder.Filters.Count > 0)
                    dgvList.DataSource = _sqlBuilder.Filters;
            }
        }

        protected void dgvList_UpdateCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            //Set new values
            Hashtable newValues = new Hashtable();
            ucSetValueFilter userControl = (ucSetValueFilter)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);

            RadComboBox txtFrom = userControl.FindControl("txtFrom") as RadComboBox;
            RadNumericTextBox numFrom = userControl.FindControl("numFrom") as RadNumericTextBox;
            RadDatePicker dpFrom = userControl.FindControl("dpFrom") as RadDatePicker;

            RadComboBox txtTo = userControl.FindControl("txtTo") as RadComboBox;
            RadNumericTextBox numTo = userControl.FindControl("numTo") as RadNumericTextBox;
            RadDatePicker dpTo = userControl.FindControl("dpTo") as RadDatePicker;

            //The GridTableView will fill the values from all editable columns in the hash
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
            int indexUpdate = editedItem.ItemIndex;

            if (Session["sqlbuilder"] != null)
            {
                _sqlBuilder = (SQLBuilder)Session["sqlbuilder"];
                switch (_sqlBuilder.Filters[indexUpdate].Node.FType)
                {
                    case "N":
                    case "N1":
                    case "N2":
                    case "N3":
                    case "N4":
                    case "SPN":
                        _sqlBuilder.Filters[indexUpdate].ValueFrom = _sqlBuilder.Filters[indexUpdate].FilterFrom = numFrom.Value.ToString();
                        _sqlBuilder.Filters[indexUpdate].ValueTo = _sqlBuilder.Filters[indexUpdate].FilterTo = numTo.Value.ToString();
                        break;
                    case "SDN":
                        _sqlBuilder.Filters[indexUpdate].ValueFrom = _sqlBuilder.Filters[indexUpdate].FilterFrom = BUS.CommonControl.ConvertDateToInt(dpFrom.SelectedDate).ToString();
                        _sqlBuilder.Filters[indexUpdate].ValueTo = _sqlBuilder.Filters[indexUpdate].FilterTo = BUS.CommonControl.ConvertDateToInt(dpTo.SelectedDate).ToString();
                        break;
                    default:
                        _sqlBuilder.Filters[indexUpdate].ValueFrom = _sqlBuilder.Filters[indexUpdate].FilterFrom = txtFrom.Text.ToString();
                        _sqlBuilder.Filters[indexUpdate].ValueTo = _sqlBuilder.Filters[indexUpdate].FilterTo = txtTo.Text.ToString();
                        break;
                }

                Session["sqlbuilder"] = _sqlBuilder;
            }
            //dgvList.Rebind();
        }



        protected void dgvList_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName.ToUpper() == "LOAD")
            {

                //frmFilter.EnableViewState = false;
                ////frmFilter.NavigateUrl = ResolveUrl(string.Format(url, Args));
                //frmFilter.VisibleOnPageLoad = true;
            }
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {

        }


    }
}
